package com.jlpay.open.jlpay.sdk.java.enums;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.jlpay.open.jlpay.sdk.java.utils.gm.Sm3Utils;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/***
 * 摘要算法类型
 * @author xuexiaoya
 * @date 2024/3/4
 **/
public enum DigestAlgorithmType {

    /**
     * SM3
     */
    SM3("SM3"),

    /**
     * SM4
     */
    SHA256("sha256"),

    ;

    private final String value;

    DigestAlgorithmType(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    private static final Map<String, DigestAlgorithmType> MAP = new HashMap<>();


    static {
        for (DigestAlgorithmType cryptoType : values()) {
            MAP.put(cryptoType.value, cryptoType);
        }
    }

    @JsonCreator
    public static DigestAlgorithmType getType(String value) {
        return MAP.get(value);
    }


    /**
     * 计算摘要
     *
     * @param type
     * @param bytes
     * @return
     */
    public static String getDigestByType(DigestAlgorithmType type, byte[] bytes) {
        byte[] message = null;
        if (SM3.equals(type)) {
            message = Sm3Utils.hash(bytes);
        }
        if (SHA256.equals(type)) {
            message = DigestUtils.sha256(bytes);
        }
        return Base64.getEncoder().encodeToString(message);
    }
}
